package com.tbit.uqbike.robot.net.aio.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public abstract class ReadHandler implements CompletionHandler<Integer, ByteBuffer> {
    protected AsyncClientHandler client;
    private ByteBuffer readBuffer;// 接收缓冲区
    private int analyzeBufferSize;

    public ReadHandler(AsyncClientHandler client) {
        this.client = client;
        this.readBuffer = ByteBuffer.allocate(this.client.getiRecvBufferSize());
    }

    public void beginRead() {
        readBuffer.clear();
        client.getClientChannel().read(readBuffer, readBuffer, this);
    }

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        // 收到字节为0表示断开连接了
        if (result > 0) {
            analyzeBufferSize += result;
            TcpClientTest.recvCnt.addAndGet(analyzeBufferSize / 12);
            analyzeBufferSize = analyzeBufferSize % 12;
            buffer.flip();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            handleRecv(bytes);
            try {
                beginRead();// 收到后继续接收
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 如果走到这里说明有问题 直接关闭链路
        client.closeConnect();
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        client.closeConnect();
    }

    public abstract void handleRecv(byte[] data);
}